<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>按字符串属性排序对象</title>
</head>

<body>
    <h1>JavaScript 数组排序</h1>
    <p>点击按钮按车型对汽车进行排序：</p>
    <button onclick="myFunction()">排序</button>
    <p id="demo"></p>
    <script>
        var cars = [
            { type: "W", year: 2017 },
            { type: "i", year: 2019 },
            { type: "e", year: 2018 }
        ];

        displayCars();

        function myFunction() {
            cars.sort(function (a, b) {
                var x = a.type.toLowerCase();
                var y = b.type.toLowerCase();
                if (x < y) { return -1; }
                if (x > y) { return 1; }
                return 0;
            });
            displayCars();
        }

        function displayCars() {
            document.getElementById("demo").innerHTML =
                cars[0].type + " " + cars[0].year + "<br>" +
                cars[1].type + " " + cars[1].year + "<br>" +
                cars[2].type + " " + cars[2].year;
        }
    </script>
</body>

</html>